<template>
  <div
    class="right-panel"
    :style="{ width: `${panelWidth}px`, padding: panelWidth > 0 ? '24px' : 0 }"
  >
    <div class="panel-header">
      <span>{{ currentItem?.name || '组件属性' }}</span>
    </div>
    <div class="panel-content">
      <!-- 栅格布局配置 -->
      <template v-if="currentItem?.type === 'grid'">
        <div class="box">
          <div class="title2">基础配置</div>
          <el-form-item label="列数">
            <el-input-number 
              v-model="currentItem.options.colNum" 
              :min="1" 
              :max="4"
              @change="handleColNumChange"
            />
          </el-form-item>
          <el-form-item label="列间距">
            <el-input-number 
              v-model="currentItem.options.gutter" 
              :min="0" 
              :max="40"
              :step="8"
            />
          </el-form-item>
          <el-form-item label="水平对齐">
            <el-select v-model="currentItem.options.justify">
              <el-option label="左对齐" value="start" />
              <el-option label="居中对齐" value="center" />
              <el-option label="右对齐" value="end" />
              <el-option label="两端对齐" value="space-between" />
              <el-option label="环绕对齐" value="space-around" />
            </el-select>
          </el-form-item>
          <el-form-item label="垂直对齐">
            <el-select v-model="currentItem.options.align">
              <el-option label="顶部对齐" value="top" />
              <el-option label="居中对齐" value="middle" />
              <el-option label="底部对齐" value="bottom" />
            </el-select>
          </el-form-item>
        </div>
        <div class="box">
          <div class="title2">列配置</div>
          <div 
            v-for="(col, index) in currentItem.options.columns" 
            :key="index"
            class="column-config"
          >
            <div class="flex-box">
              <span class="title3">列{{ index + 1 }}</span>
              <el-form-item :label="`列${index + 1}宽度`">
                <el-input-number 
                  v-model="col.span" 
                  :min="1" 
                  :max="24"
                  :step="1"
                />
              </el-form-item>
              <el-form-item :label="`列${index + 1}偏移`">
                <el-input-number 
                  v-model="col.offset" 
                  :min="0" 
                  :max="24"
                  :step="1"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </template>

      <!-- 卡片布局配置 -->
      <template v-else-if="currentItem?.type === 'card'">
        <div class="box">
          <div class="title2">基础配置</div>
          <el-form-item label="标题">
            <el-input v-model="currentItem.options.title" />
          </el-form-item>
          <el-form-item label="显示标题">
            <el-switch v-model="currentItem.options.showHeader" />
          </el-form-item>
          <el-form-item label="阴影">
            <el-select v-model="currentItem.options.shadow">
              <el-option label="始终显示" value="always" />
              <el-option label="悬浮显示" value="hover" />
              <el-option label="从不显示" value="never" />
            </el-select>
          </el-form-item>
        </div>
      </template>

      <!-- 其他组件配置 -->
      <template v-else>
        <!-- 基础配置 -->
        <div class="box" v-if="type">
          <div class="title2">基础配置</div>
          <el-form-item label="必填">
            <el-switch
              v-model="newCurrentItem.options.required"
              @change="(e) => requireRuleChange(e, newCurrentItem)"
            />
          </el-form-item>
          <el-form-item label="只读">
            <el-switch v-model="newCurrentItem.options.readonly" />
          </el-form-item>
          <el-form-item label="禁用">
            <el-switch v-model="newCurrentItem.options.disabled" />
          </el-form-item>
          <el-form-item label="占位提示">
            <el-input v-model="newCurrentItem.options.placeholder" />
          </el-form-item>
        </div>
        
        <!-- 文本输入配置 -->
        <div class="box" v-if="type === 'single-input' || type === 'textarea'">
          <div class="title2">文本配置</div>
          <el-form-item label="字数限制">
            <el-switch v-model="newCurrentItem.options.showWordLimit" />
          </el-form-item>
          <el-form-item label="最大长度" v-if="newCurrentItem.options.showWordLimit">
            <el-input-number v-model="newCurrentItem.options.maxlength" :min="1" />
          </el-form-item>
          <!-- ... 其他文本配置 ... -->
        </div>
        
        <!-- 数值配置 -->
        <div class="box" v-if="type === 'number' || type === 'amount'">
          <div class="title2">数值配置</div>
          <el-form-item label="最小值">
            <el-input-number 
              v-model="newCurrentItem.options.minValue"
              @change="numberMinChange"
            />
          </el-form-item>
          <el-form-item label="最大值">
            <el-input-number 
              v-model="newCurrentItem.options.maxValue"
              @change="numberMaxChange"
            />
          </el-form-item>
          <!-- ... 其他数值配置 ... -->
        </div>
        
        <!-- 选择器配置 -->
        <div class="box" v-if="type === 'single-select' || type === 'multi-select'">
          <div class="title2">选项配置</div>
          <draggable
            v-model="newCurrentItem.selectOptions"
            item-key="value"
            handle=".icon"
            animation="300"
          >
            <template #item="{ element, index }">
              <div class="flex-box drag-li">
                <el-icon class="icon"><DArrowRight /></el-icon>
                <el-input v-model="element.label" placeholder="选项名" />
                <el-icon @click="closeSelectOption(index)"><Delete /></el-icon>
              </div>
            </template>
          </draggable>
          <!-- ... 其他选择器配置 ... -->
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useStore } from "vuex";
import draggable from 'vuedraggable'
import { formatAmount, formatCurrency, numberMinChangeM, numberMaxChangeM } from '../../../../utils'
import { ElMessage } from 'element-plus'
import { useJudgeNumberRange, useJudgeOptionFit } from './hooks/judge.js'
// import { useFormStore } from '@/stores/form'

/* ts类型定义区域 */

/* 定义数据区域 */
const props = defineProps({
  currentItem: {
    type: Object,
    default: () => {}
  }
})
const store = useStore();
const newCurrentItem = ref<any>({})
const type = ref('')
const panelWidth = ref(0)
const judgeIsFix = useJudgeNumberRange(newCurrentItem) // 判断设置数值/金额时的提示警告显示/隐藏
const judgeOptionFix = useJudgeOptionFit(newCurrentItem) // 判断单选/多选时的提示警告显示/隐藏
//const formStore = useFormStore()

/* 事件处理区域 */
// 删除下拉选项处理
const closeSelectOption = (index: number) => {
  if (newCurrentItem.value.selectOptions.length === 1) {
    ElMessage({
      message: '至少需要一项',
      type: 'warning'
    })
    return
  }
  const filter = newCurrentItem.value.selectOptions.splice(index, 1)

  if (filter[0].value === newCurrentItem.value.options.defaultValue) {
    newCurrentItem.value.options.defaultValue = null
  }
}

/** 校验效果 */
const requireRuleChange = (event: any, newCurrentItem: any) => {
  let tempRules: any[] = []

  if (event) {
    tempRules = [
      {
        required: true,
        message: newCurrentItem.options.rulesConfig.messageTip,
        trigger: newCurrentItem.options.rulesConfig.trigger
      }
    ]
  } else {
    tempRules = []
  }

  newCurrentItem.options.rulesConfig.rules = tempRules
}

// 默认值切换，重置填写/选择的默认值
const showDefaultSwitch = (value: boolean) => {
  if (!value) {
    newCurrentItem.value.options.defaultValue = ''
  }
}

/** 数字相关 */
const numberMinChange = (value: string) => {
  //formStore.computeErrorContent()
  numberMinChangeM(value, newCurrentItem)
  requireRuleChange(newCurrentItem.value.options.required, newCurrentItem.value)
}

const numberMaxChange = (value: string) => {
  //formStore.computeErrorContent()
  numberMaxChangeM(value, newCurrentItem)
  requireRuleChange(newCurrentItem.value.options.required, newCurrentItem.value)
}

const rightPanelChange = (e: any, id: string) => {
  console.log(e, id,newCurrentItem.value)
  newCurrentItem.value[id] = e
  //formStore.computeErrorContent()
}

const rightPanelChangeDefaultValue = (e: any, id: string) => {
  console.log(e, id,newCurrentItem.value)
  newCurrentItem.value.options[id] = e
  //formStore.computeErrorContent()
}

/* 监听 */
watch(
  () => store.state.form.selectFormItem,
  (newVal) => {
    console.log('newVal', newVal)
    if (newVal?.name) {
      newCurrentItem.value = newVal
      type.value = newVal.type
      panelWidth.value = 300
    } else {
      newCurrentItem.value = newVal ?? {}
      panelWidth.value = 0
    }
  }
)

// watch(
//   () => props.currentItem,
//   (newVal) => {
//     console.log('newVal', newVal)
//     if (newVal?.name) {
//       newCurrentItem.value = newVal
//       type.value = newVal.type
//       panelWidth.value = 300
//     } else {
//       newCurrentItem.value = newVal ?? {}
//       panelWidth.value = 0
//     }
//   }
// )

/* 生命周期 */

// 处理列数变化
const handleColNumChange = (value) => {
  const columns = newCurrentItem.value.options.columns
  const oldNum = columns.length
  
  if (value > oldNum) {
    // 增加列
    const diff = value - oldNum
    for (let i = 0; i < diff; i++) {
      columns.push({
        span: Math.floor(24 / value),
        offset: 0,
        push: 0,
        pull: 0,
        list: []
      })
    }
  } else if (value < oldNum) {
    // 减少列，将多余列的组件合并到最后一列
    const removedCols = columns.splice(value)
    const lastCol = columns[columns.length - 1]
    removedCols.forEach(col => {
      if (col.list && col.list.length) {
        lastCol.list.push(...col.list)
      }
    })
  }
  
  // 重新计算每列宽度
  columns.forEach(col => {
    col.span = Math.floor(24 / value)
  })
}
</script>

<style lang="less" scoped>
.gray-color {
  color: #8f959e;
}
.right-panel {
  // width: 300px;
  height: 100%;
  padding: 16px;
  background-color: #fff;
  transition: width 300ms;
  .title {
    font-size: 18px;
    line-height: 28px;
    color: #1f2329;
    font-weight: 500;
    margin-bottom: 16px;
  }
  .box {
    margin-bottom: 20px;
    position: relative;
    .title2 {
      color: #1f2329;
      font-size: 14px;
      line-height: 20px;
      margin-bottom: 8px;

      span {
        position: relative;
        &::after {
          content: '*';
          position: absolute;
          left: 100%;
          top: -2px;
          line-height: 20px;
          padding-left: 2px;
          color: #f54a45;
        }
      }
    }
    .title3 {
      margin-right: 5px;
    }
    .default-input {
      margin-bottom: 16px;
    }
    .tip {
      color: #f54a45;
      font-size: 12px;
      line-height: 32px;
      height: 20px;
      margin-bottom: 12px;
    }
    .over-tip {
      padding-left: 24px;
      color: #f54a45;
      font-size: 12px;
      line-height: 32px;
      height: 20px;
      margin-bottom: 12px;
    }
    .preview {
      display: flex;
      background: #f2f3f5;
      border-radius: 4px;
      padding: 12px 16px;
      display: flex;
      color: #1f2329;
      font-size: 14px;
      .example {
        color: #8f959e;
        font-size: 14px;
      }
    }
    .operate {
      display: flex;
      align-items: center;
      margin-left: 24px;
      color: #3370ff;
      cursor: pointer;
      span {
        margin-left: 3px;
        padding-top: 1px;
      }
    }

    .drag-li {
      margin-bottom: 10px;
    }
  }
  .box2 {
    margin-bottom: 10px;
  }
  .flex-box {
    display: flex;
    align-items: center;

    .divider {
      margin: 0 5px;
    }
    .divider-input {
      width: 100px;
      margin: 0 5px;
    }

    .divider-input2 {
      margin: 0 5px;
    }

    .icon {
      font-size: 20px;
      cursor: move;
    }

    .slider {
      margin-left: 10px;
    }
  }
}
:deep(.el-textarea__inner) {
  height: 100px;
}

// 错误提示框
.is-error {
  :deep(.el-input__wrapper) {
    box-shadow: inset 0 0 0 1px #f5222d;
  }
}

.column-config {
  background: #f8f9fa;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .flex-box {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .title3 {
      min-width: 40px;
      color: #606266;
    }
    
    :deep(.el-input-number) {
      width: 100px;
    }
  }
}
</style>